using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[CreateAssetMenu(menuName = "SOInstance/Data/FightWaveData")]
public class FightWaveData : ScriptableObject
{
    public List<FightWaveSubData> subs;

    public IEnumerator FightWave(Transform parent, float delayTime, Action onCheck, Action onComplete = null)
    {
        //Debug.Log($"WaitForSeconds : {delayTime}");
        yield return new WaitForSeconds(delayTime);
        //Debug.Log("Start Wave");
        int checkCounter = 0;
        int waveCounter = 0;

        foreach (var sub in subs)
        {
            for (int i = 0; i < sub.count; i++)
            {
                GameObject obj = Instantiate(sub.prefab);
                obj.transform.SetParent(parent);
                obj.transform.position = Util.GetRandomPos_Rect(sub.pos, sub.posAreaSize);
                Enemy enemy = obj.GetComponent<Enemy>();
                enemy.patrolArea = parent.GetComponent<PolygonCollider2D>();

                waveCounter++;
                enemy.OnThisDeath += () =>
                {
                    //Debug.Log($"chek {checkCounter} wave {waveCounter}");
                    if (--waveCounter == 0)
                    {
                        //Debug.Log("Finish Wave");
                        onComplete?.Invoke();
                    }
                };

                if (sub.isCheckPoint)
                {
                    checkCounter++;
                    enemy.OnThisDeath += () =>
                    {
                        if (--checkCounter == 0)
                        {
                            //Debug.Log("Finish Check");
                            onCheck?.Invoke();
                        }
                    };
                }

            }
        }
    }
}